<script setup lang="ts">
import { useLayoutConfigStore } from '@/store/layoutConfig'
import type { RouteLocationNormalized, RouteRecordNormalized } from 'vue-router'

/**
 * 第一次加载触发
 */
const route = useRoute()
const router = useRouter()
onMounted(() => {
  getBreadcrumb(route)
})

/**
 * 路由更新时会触发
 */
onBeforeRouteUpdate((to) => {
  getBreadcrumb(to)
})

/**
 * 获取当前路由的面包屑
 * @param to 目标路由对象 
 */
const breadcrumbList = ref<RouteRecordNormalized[]>([])
function getBreadcrumb(to: RouteLocationNormalized) {
  // console.log('getBreadcrumb', to.matched);
  const matched = to.matched.filter(item => item.meta && item.meta.title && item.meta.isBreadcrumd)
  // console.log('getBreadcrumb', matched);
  breadcrumbList.value = matched
}

/**
 * 展开/折叠
 */
const layoutConfigStore = useLayoutConfigStore()
const { isCollapse } = storeToRefs(layoutConfigStore)
function handleChangeCollapse() {
  isCollapse.value = !isCollapse.value
}

/**
 * 点击标题路由跳转
 */
function handleLink(_route: RouteRecordNormalized) {
  const { redirect, path } = _route
  console.log(redirect, path);
  if (redirect) {
    router.push(redirect as string)
  } else {
    router.push(path)
  }
}

</script>

<template>
  <div class="layout-header-breadcrumb ">
    <!-- 收缩图标 -->
    <SvgIcon @click="handleChangeCollapse" width="17" height="17" :name="isCollapse ? 'expand' : 'fold'"
      class="layout-header-expand-icon" />
    <el-breadcrumb separator="/">
      <el-breadcrumb-item v-for="(item, index) in breadcrumbList" :key="item.path">
        <span v-if="index === breadcrumbList.length - 1" class="flex-center">
          {{ item.meta.title }}
        </span>
        <a v-else @click.prevent="handleLink(item)" class="flex-center">
          {{ item.meta.title }}
        </a>
      </el-breadcrumb-item>
    </el-breadcrumb>
  </div>
</template>

<style scoped lang="scss"></style>